const http = require("http");
const url = require("url");
const fs = require("fs");
const zlib = require("zlib");

http.createServer((req,res)=>{
  let {pathname}=url.parse(req.url);
  fs.stat(`webapps${pathname}`, (err, stat)=>{
  if(err){
      res.writeHeader(404);
      res.write('Not Found');
      res.end();
    }else{
      //由浏览器传过来
      if(req.headers['if-modified-since']){
        let oDate=new Date(req.headers['if-modified-since']);
        let time_client=Math.floor(oDate.getTime()/1000);

        let time_server=Math.floor(stat.mtime.getTime()/1000);

        if(time_server>time_client){      //服务器的文件时间>客户端手里的版本
          send();
        }else{
          res.writeHeader(304);
          res.write('Not Modified');
          res.end();
        }
      }else{
        send();
      }
    }
  function send(){
    let  rs = fs.createReadStream(`webapps${pathname}`);
    let gz = zlib.createGzip();
    res.setHeader('content-encoding', 'gzip');
    //res.setHeader('Cache-Control', 'no-cache,no-store');//先要清一遍缓存才生效
    res.setHeader('Last-Modified', stat.mtime.toGMTString());
    rs.pipe(gz).pipe(res);
    rs.on('error',err=>{
      res.writeHeader(404);
      res.write('Not Found');
      res.end();
    })
  }
  
  })
}).listen(8080);
